package com.falcon.mvc.core;

import com.falcon.mvc.constant.ResponseHeaderConstant;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;

public class ResponseWrapper extends HttpServletResponseWrapper {

    private ByteArrayOutputStream buffer = null;
    private ServletOutputStream out = null;
    private PrintWriter writer = null;

    public ResponseWrapper(HttpServletResponse resp) throws IOException {
        super(resp);
        // 真正存储数据的流
        buffer = new ByteArrayOutputStream();
        out = new WrappedOutputStream(buffer);
        writer = new PrintWriter(new OutputStreamWriter(buffer, this.getCharacterEncoding()));
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return out;
    }

    @Override
    public PrintWriter getWriter() throws UnsupportedEncodingException {
        return writer;
    }

    @Override
    public void flushBuffer() throws IOException {
        if (out != null) {
            out.flush();
        }
        if (writer != null) {
            writer.flush();
        }
    }

    @Override
    public void reset() {
        buffer.reset();
    }

    public byte[] getResponseData() throws IOException {
        flushBuffer();
        return buffer.toByteArray();
    }

    /** 是否发生异常 */
    public boolean isOccurError() {
        return "true".equals(this.getHeader(ResponseHeaderConstant.OCCUR_ERROR));
    }

    /** 异常码 */
    public int getErrorCode() {
        String errorCode = this.getHeader(ResponseHeaderConstant.ERROR_CODE);
        return StringUtils.hasText(errorCode) ? Integer.valueOf(errorCode) : 0;
    }

    /** 异常描述 */
    public String getErrorMessage() {
        return this.getHeader(ResponseHeaderConstant.ERROR_CODE);
    }

    private static class WrappedOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream bos = null;

        public WrappedOutputStream(ByteArrayOutputStream stream) throws IOException {
            bos = stream;
        }

        @Override
        public void write(int b) throws IOException {
            bos.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            bos.write(b, 0, b.length);
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }
    }

}
